/*
 * Copyright (C) 2011 Mette Bank, Rikke Jensen, Kenneth Brodersen, Thomas Pedersen
 * 
 * This file is part of digiPECS.
 * 
 * digiPECS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * digiPECS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with digiPECS.  If not, see <http://www.gnu.org/licenses/>.
 */

package sw6.digipecs.admin;

import java.util.ArrayList;
import java.util.List;

import sw6.digipecs.R;
import sw6.digipecs.exceptions.DatabaseException;
import sw6.digipecs.exceptions.ImageIsEmptyException;
import sw6.digipecs.model.ExtImageInSituation;
import sw6.digipecs.model.Situation;
import sw6.digipecs.widget.admin.HelpView;
import sw6.digipecs.widget.admin.SelectableExtImageAdapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.Spinner;

public class ManageSituationsActivity extends Activity implements
		OnItemSelectedListener, OnClickListener, OnItemClickListener {
	private Context mContext;
	private List<Situation> mSituationsList;
	private GridView mImageGrid;
	private Spinner mSelectSituationSpinner;
	private SelectableExtImageAdapter<ExtImageInSituation> mImagesAdapter;
	private Situation mSelectedSituation;
	private boolean mIsDefaultSelected = false;
	private ImageButton mAddImagesButton;
	private ImageButton mDeleteImagesButton;
	private ArrayList<ExtImageInSituation> mImageList;
	private String[] mSituationArray;
	private int mActiveSituationId = -1;
	private int mActiveSituationPos = -1;
	private HelpView mHelpView;

	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.managesituationsmainlayout);
		initialise();
	}

	private void initialise() {

		mContext = getApplicationContext();
		mSelectSituationSpinner = (Spinner) findViewById(R.id.selectSituationSpinner);
		mSelectSituationSpinner.setOnItemSelectedListener(this);
		mImageGrid = (GridView) findViewById(R.id.situationImagesGrid);
		mImageGrid.setOnItemClickListener(this);
		
		mHelpView = (HelpView)findViewById(R.id.helperManageSituations); 
		mHelpView.setHeadText("Håndter Situationer"); 
		mHelpView.setBodyText("Her kan situationer oprettes, fjernes og manipuleres \n" +
				"- Brug drop down boksen til at vælge situation \n" +
				"- Brug knapperne i toppen ti lat tilføje/fjerne billeder til/fra en valgt situation \n" +
				"- Tryk på et billede for at aktivere/deaktivere det i bogen \n" +
				"- Brug menu-knappen på enheden for at oprette/fjerne en situation"); 
		
		try {
			mActiveSituationId = Situation.getActiveSituation(mContext);
		} catch (DatabaseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mAddImagesButton = (ImageButton) findViewById(R.id.addImagesToSituationButton);
		mAddImagesButton.setOnClickListener(this);
		mDeleteImagesButton = (ImageButton) findViewById(R.id.removeImagesFromSituationButton);
		mDeleteImagesButton.setOnClickListener(this);
		updateSpinner(-1);
	}
	@Override
	protected void onResume() {
		//initialise(); 
		super.onResume();
	}
	
	private void updateImageGridView() {
		Log.w("sw6", "I was run...");
		
		synchronized (this) {
			mImageList = new ArrayList<ExtImageInSituation>();
			ArrayList<ExtImageInSituation> images = mSelectedSituation.getAllPictures(mContext);
			for (ExtImageInSituation image : images) {
				boolean state;
				try {
					state = image.isActive();
					image.setIsSelected(state);
					mImageList.add(image);
				} catch (ImageIsEmptyException e) {
					Log.e("sw6", "This should not happen (View stack trace)");
					e.printStackTrace();
				}
			}

			mImagesAdapter = new SelectableExtImageAdapter<ExtImageInSituation>(
					mContext, mImageList,
					SelectableExtImageAdapter.SELECT_MODE_ACTIVE);
			
			mImageGrid.setAdapter(mImagesAdapter);
		}
	}

	/*private class UpdateImageGrid extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... arg0) {
			Log.w("sw6", "I was run...");
			
			synchronized (this) {
				mImageList = new ArrayList<ExtImageInSituation>();
				ArrayList<ExtImageInSituation> images = mSelectedSituation.getAllPictures(mContext);
				for (ExtImageInSituation image : images) {
					boolean state;
					try {
						state = image.isActive();
						image.setIsSelected(state);
						mImageList.add(image);
					} catch (ImageIsEmptyException e) {
						Log.e("sw6", "This should not happen (View stack trace)");
						e.printStackTrace();
					}
				}

				mImagesAdapter = new SelectableImageAdapter<ExtImageInSituation>(
						mContext, mImageList,
						SelectableImageAdapter.SELECT_MODE_ACTIVE);
			}
			
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			mImageGrid.setAdapter(mImagesAdapter);
		}
	}*/

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.managesituationoptionsmenu, menu);
		return true;

	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		MenuItem deleteItem = menu.getItem(1);
		MenuItem editItem = menu.getItem(2); 
		if (mIsDefaultSelected)
		{
			deleteItem.setEnabled(false);
			editItem.setEnabled(false); 
		}
		else
		{
			deleteItem.setEnabled(true);
			editItem.setEnabled(true); 
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.situationListContextMenuItemAdd:
			CreateSituation();
			return true;
		case R.id.situationListContextMenuItemDelete:
			deleteSituation();
			return true;
		case R.id.situationListContextMenuitemEdit:
			editSituationText(); 
			return true;
		}
		return false;
	}

	private void editSituationText() {
		Intent intent = new Intent(this,EditSituationNameActivity.class); 
		intent.putExtra(EditSituationNameActivity.SITUATION_ID, mSelectedSituation.getId()); 
		startActivityForResult(intent, EditSituationNameActivity.REQUEST_CODE); 
	}

	private void deleteSituation() {
		mSelectedSituation.delete();
		mSelectedSituation = null;
		updateSpinner(-1);
	}

	private void CreateSituation() {
		Intent intent = new Intent(this, CreateSituationActivity.class);
		startActivityForResult(intent,
				CreateSituationActivity.CREATE_SITUATION_REQUEST_CODE);
	}

	private void updateSpinner(int pos) {
		mSituationsList = Situation.getAll(mContext);
		mSituationArray = new String[mSituationsList.size()];
		int i = 0;
		for (Situation s : mSituationsList) {
			mSituationArray[i] = s.getName();
			if (s.getId() == mActiveSituationId)
				mActiveSituationPos = i;
			i++;
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext,
				android.R.layout.simple_spinner_dropdown_item, mSituationArray);
		mSelectSituationSpinner.setAdapter(adapter);
		if (pos<=0) {
			mSelectSituationSpinner.setSelection(mActiveSituationPos);
		} else {
			mSelectSituationSpinner.setSelection(pos);
		}
		adapter.notifyDataSetChanged(); 
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case CreateSituationActivity.CREATE_SITUATION_REQUEST_CODE:
			if(resultCode==RESULT_OK)
				updateSpinner(mSituationsList.size());
			break;
		case AddImagesToSituationActivity.REQUEST_CODE:
			updateImageGridView();
			break;
		case RemoveImagesFromSituationActivity.REQUEST_CODE:
			updateImageGridView();
		case EditSituationNameActivity.REQUEST_CODE:
			int pos = mSelectSituationSpinner.getSelectedItemPosition(); 
			updateSpinner(pos); 
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		int pos = mSelectSituationSpinner.getSelectedItemPosition();
		mSelectedSituation = mSituationsList.get(pos);
		if (pos == 0) {
			mIsDefaultSelected = true;
			mAddImagesButton.setEnabled(false);
			mDeleteImagesButton.setEnabled(false);
		} else {
			mIsDefaultSelected = false;
			mAddImagesButton.setEnabled(true);
			mDeleteImagesButton.setEnabled(true);
		}
		updateImageGridView();
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {

	}

	@Override
	public void onClick(View arg0) {
		Intent intent = null;
		switch (arg0.getId()) {
		case R.id.addImagesToSituationButton:
			intent = new Intent(this, AddImagesToSituationActivity.class);
			intent.putExtra(AddImagesToSituationActivity.SITUATION_ID,
					mSelectedSituation.getId());
			startActivityForResult(intent,
					AddImagesToSituationActivity.REQUEST_CODE);
			break;
		case R.id.removeImagesFromSituationButton:
			intent = new Intent(this, RemoveImagesFromSituationActivity.class);
			intent.putExtra(RemoveImagesFromSituationActivity.SITUATION_ID,
					mSelectedSituation.getId());
			startActivityForResult(intent,
					RemoveImagesFromSituationActivity.REQUEST_CODE);
			break;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		ExtImageInSituation selectedImage = mImageList.get(arg2);
		Boolean currentSelectState = selectedImage.isSelected();

		try {
			selectedImage.setActive(!currentSelectState);
			selectedImage.setIsSelected(!currentSelectState);
			mImageList.set(arg2, selectedImage);
			mImagesAdapter.notifyDataSetChanged();
		} catch (ImageIsEmptyException e) {
			Log.e("sw6", "This should not happen (View stack trace)");
			e.printStackTrace();
		}
	}

}
